package com.tudouji.project.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.flow.service.utils.DateUtils;
import com.tudouji.common.constant.Constants;
import com.tudouji.common.constant.UserConstants;
import com.tudouji.common.enums.UserTypeEnums;
import com.tudouji.common.exception.CustomException;
import com.tudouji.common.exception.user.UserPasswordNotMatchException;
import com.tudouji.common.utils.*;
import com.tudouji.common.utils.ip.IpUtils;
import com.tudouji.framework.config.EncrypAES;
import com.tudouji.framework.manager.AsyncManager;
import com.tudouji.framework.manager.factory.AsyncFactory;
import com.tudouji.framework.redis.RedisCache;
import com.tudouji.framework.security.LoginUser;
import com.tudouji.framework.security.service.SysLoginService;
import com.tudouji.framework.security.service.SysPermissionService;
import com.tudouji.framework.security.service.TokenService;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.domain.server.Sys;
import com.tudouji.project.organization.domain.Supplier;
import com.tudouji.project.organization.mapper.SupplierMapper;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.domain.Tmessage;
import com.tudouji.project.system.domain.Tuser;
import com.tudouji.project.system.domain.Upimage;
import com.tudouji.project.system.service.ISysUserService;
import com.tudouji.project.system.service.ITmessageService;
import com.tudouji.project.system.service.ITuserService;
import com.tudouji.project.wechat.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.weixin4j.component.SnsComponent;
import org.weixin4j.model.sns.SnsAccessToken;
import org.weixin4j.spring.WeixinTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author wf
 * @date 2021年05月26日 16:23
 */
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private WeixinTemplate weixinTemplate;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ITuserService tuserService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private MessageUitls messageUitls;

    @Autowired
    private ITmessageService messageService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SupplierMapper supplierMapper;

    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        try {
            SnsComponent snsComponent = weixinTemplate.sns();
            SnsAccessToken token = snsComponent.getSnsOAuth2AccessToken(code);
            return token.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            return null;
        }
    }

    /**
     * 微信登录
     *
     * @param username
     * @param password
     * @param openid
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String username, String password, String openid, Boolean menu){
        logger.error("params_openid: " + openid);
        SysUser user = userService.selectUserByUserName(username);
        if (null == user && !menu) {
            return AjaxResult.error("用户尚未注册");
        }
        //20230313 调用login完成登录，不需要再验证密码，login方法会验证
        String token=login(username,password,user);

        //if (!SecurityUtils.matchesPassword(password, user.getPassword())){
        //    return AjaxResult.error("用户密码错误");
        //}
        //sysLoginService.checkPwd(username, password);
        //LoginUser loginUser = autho2(username, password);
        //PC微信端登录
        // 20230313 不管是pc微信端、还是微信端登录，都需要清掉openId以前对应的用户的openid
        SysUser usered = userService.selectUserByOpenid(openid);
        if (StringUtils.isNotNull(usered)) {
            if (!usered.getPhonenumber().equalsIgnoreCase(username.trim())) {
                usered.setOpenid("");
                userService.updateUserPoJo(usered);
                user.setOpenid(openid);
                userService.updateUserPoJo(user);
            }
        } else {
            user.setOpenid(openid);
            userService.updateUserPoJo(user);
        }
        //loginUser.setUser(user);
        //String token = tokenService.createToken(loginUser);
        logger.info("token:" + token);

        return AjaxResult.success(token);
    }
    /**
     * 获取验证码
     */
    @Override
    public AjaxResult getSmsCode(String phoneNumber){
        SysUser user =  userService.selectUserByUserName(phoneNumber);
//        if (StringUtils.isNotEmpty(phoneNumber) && StringUtils.isNotNull(user))return AjaxResult.error("手机号码已存在！");
        AjaxResult result = new AjaxResult();
        String code = Math.round( Math.random() * 8999 + 1000 ) + "";
        String context = "您的验证码是:" + code + "。请不要把验证码泄露给其他人。如非本人操作，可不用理会！";// 短信消息
        Tmessage tmessage = new Tmessage();
        tmessage.setContext( context );// 短信内容
        tmessage.setSenddate( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).format( new Date() ) );// 发送时间
        tmessage.setPhonenum( phoneNumber );// 手机号
        JSONObject object = new JSONObject();
        object.put("code", code);
        int res = messageUitls.sendMessage( phoneNumber, object.toJSONString(), messageUitls.getConfig().getTemplateCode_Verification());
        tmessage.setVerifycode( code );// 验证码
        if ( res >= 0 ) {// 发送成功
            messageService.insertTmessage( tmessage );
            return AjaxResult.success(code);
        }
        return AjaxResult.error();
    }

    private LoginUser autho2(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser;
    }

    /**
     * 验证码校验
     **/
    public AjaxResult checkSmsCode(String phoneNumber, String code){
        // 查询验证码是否存在
        Tmessage message = new Tmessage();
        message.setPhonenum(phoneNumber);
        message = messageService.getLastMessageByPhone(message);
        if (null != message) {
            if (null == message.getVerifycode() || "".equals(message.getVerifycode())
                    || !code.equals(message.getVerifycode())) {
                return AjaxResult.error("验证码错误！");
            }
        } else {
            return AjaxResult.error("验证码失效！");
        }
        return AjaxResult.success();
    }

    /**
     * 微信注册
     *
     * @param user
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
    public AjaxResult wechatRegist(SysUser user,String managerID) {
        SnsComponent snsComponent = weixinTemplate.sns();
        String openid = null;
        try {
            HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
            openid = (String)session.getAttribute("openid");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber()) &&
                UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("手机号码已存在！");
        }

        if (userService.selectUserByOpenid(openid) != null) {
            SysUser usered = userService.selectUserByOpenid(openid);
            usered.setOpenid("");
            userService.updateUserPoJo(usered);
        }
        String pwd = user.getPassword();
        user.setGuid(getUUId());
        user.setOpenid(openid);
        user.setPassword(EncrypAES.encrypt(user.getPassword()));
        user.setCreateTime(DateUtils.getNowDate());
        user.setUserName(user.getPhonenumber());
        //2023.08.01去掉种植户注册生成系统用户，只生成供应商
//        if (!user.getUserType().equals(UserTypeEnums.PLANTER.getCode())) {
            userService.insertUser(user);
//        }

        if (user.getUserType().equals(UserTypeEnums.PLANTER.getCode())) {
            //如果用户类型为种植户，则在公司信息表生成记录，并且将公司GUID 回传至用户信息表中
           /* Company company = new Company();
            company.setName(user.getNickName());
            company.setGuid(getUUId());
            companyService.insertCompany(company);*/
            /*SysUser us = new SysUser();
            us.setUserId(user.getUserId());
            us.setCompanyguid(company.getGuid());
            userService.updateUser(us);*/
            //种植户注册过程中，同时生成供应商信息，供应商名称、短名均为户名
            insertSupplier(user);
        }
//        if (!user.getUserType().equals(UserTypeEnums.PLANTER.getCode())) {
            LoginUser loginUser = autho2(user.getPhonenumber(), pwd);
            loginUser.setUser(user);
            loginUser.setPermissions(permissionService.getMenuPermission(user));
            String token = tokenService.createToken(loginUser);
            return AjaxResult.success(token);
//        }
//        return AjaxResult.success();
    }

    public void insertSupplier(SysUser user) {
        Supplier supplier = new Supplier();
        supplier.setName(user.getBankName());
        Supplier suppliered = supplierMapper.selectSupplierByName(user.getNickName());
        if (null != suppliered){
            throw new CustomException("供应商已存在！");
        }
        supplier.setShortname(user.getBankName());
        supplier.setUserid(user.getGuid());
        supplier.setStatus(1);
        supplier.setCreateBy(user.getUserId());
        supplier.setCreateTime(DateUtils.getNowDate());
        supplier.setType(1);
        supplier.setBank(user.getBank());
        supplier.setBankcode(user.getBankcode());
        if (StringUtils.isNotEmpty(user.getPhonenumber())){
            supplier.setContactstel(user.getPhonenumber());
        }
        supplierMapper.insertSupplier(supplier);
    }

    public static String getUUId() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "").toUpperCase();
    }

    public String getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length()
                , url.length()).append(request.getSession().getServletContext().getContextPath()).append("/").toString();
        logger.info("getCode: tempContextUrl: " + tempContextUrl);

        String redirecturl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + weixinTemplate.getAppId()
                + "&redirect_uri=" + URLEncoder.encode(tempContextUrl + "/wechat/getWxUser")
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE&connect_redirect=1#wechat_redirect";
        response.sendRedirect(redirecturl);
        return "redirect:"+redirecturl;//必须重定向，否则不能成功

    }

    @Override
    public AjaxResult logout() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNotNull(loginUser))
        {
            //清除openid for db
            SysUser user = loginUser.getUser();
            user.setOpenid("");
            userService.updateUserPoJo(user);
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        return AjaxResult.success();
    }

    public String login(String username, String password, SysUser user)
    {
        // 用户验证
        Authentication authentication = null;
        try
        {

            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
            //20230313 新登录的用户登记到SecurityContextHolder
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //20230313 密码合规性验证，当前只是校验初始密码是否已修改
//        sysLoginService.checkPwd(user, password);
        recordLoginInfo(loginUser.getUser());
        loginUser.setUser(user);

//        sysLoginService.loginOldSys(user);
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser user)
    {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);
    }

    public String adviceAuthen(String username, String password){
        SysUser user = userService.selectUserByUserName(username);

        LoginUser loginUser = autho2(username, password);
        user.setTuserId(user.getGuid());
        loginUser.setUser(user);
        String token = tokenService.createToken(loginUser);
        logger.info("token:" + token);
        return token;
    }
}

